package com.sl.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.sl.entity.PageResult;
import com.sl.entity.Result;
import com.sl.entity.StatusCode;
import com.sl.mapper.AnswerMapper;
import com.sl.pojo.*;
import com.sl.service.*;
import com.sl.vo.AnswerVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/answer")
public class AnswerController {
    @Autowired
    private AnswerService answerService;
    @Autowired
    private PaperService paperService;
    @Autowired
    private CompanyService companyService;
    @Autowired
    private UserService userService;
    @Autowired
    private PaperQuestionsService paperQuestionsService;
    @Autowired
    private QuestionService questionService;


    @PostMapping("/all")
    public Result all (@RequestBody String data){
        JSONObject jsonObject = JSONObject.parseObject(data);
        Integer page = jsonObject.getInteger("page");
        if (null ==page) {page=1;}
        Integer pageSize = jsonObject.getInteger("pageSize");
        if (null ==pageSize) {pageSize = 10;}
        Page<Answer> all = answerService.findAll(page, pageSize);
        List<AnswerVO> answerVOList=new ArrayList<>();
        for (Answer answer : all) {
            AnswerVO answerVO = answer2VO(answer);
            answerVOList.add(answerVO);
        }
        PageResult<AnswerVO> answerPageResult = new PageResult<AnswerVO>((long) answerVOList.size(), answerVOList);
        return  new Result(true, StatusCode.OK,"所有问卷信息",answerPageResult);}

    /**
     * 根据企业ID创建问卷
     * @param data
     * @return
     */
    @PostMapping("/adds")
    public Result addCheckInfo(@RequestBody String data){
        log.info("创建问卷任务,1条或N条>>>>" );
        //取得所有公司的ID。集合
        //取得发起人userID。
        //取得问卷paperId。
        JSONObject jsonObject = JSONObject.parseObject(data);
        JSONArray enterpriseIds = jsonObject.getJSONArray("enterpriseIds");
        Integer userId = jsonObject.getInteger("userId");
        Integer paperId = jsonObject.getInteger("paperId");
        System.out.println(enterpriseIds + ">>userId>>" + userId + ">>paperId>>" + paperId);
        for (Object enterpriseId : enterpriseIds) {
            Answer answer = new Answer();
            answer.setEnterpriseId((Integer)enterpriseId);
            answer.setUserId(userId);
            answer.setPaperId(paperId);
            answer.setStartTime(LocalDateTime.now());
            answer.setStatus("检测中");//待检测，检测中，已完成
            answerService.addAnswer(answer);
        }
        return  new Result(true, StatusCode.OK,"创建问卷任务成功");
    }

    @PostMapping("/search")
    public Result findList(@RequestBody String data){
        log.info("多条件搜索检查结果");
        Map map = JSON.parseObject(data, Map.class);
      /*  String enterpriseName = jsonObject.getString("enterpriseName");
        Company companyByName = companyService.findByName(enterpriseName);
        Integer companyId = companyByName.getId();
        String userName = jsonObject.getString("userName");
        User userByName = userService.findByUsername(userName);
        Integer userId = userByName.getId();
        Map map=  new HashMap();
        map.put("enterpriseId",companyId);
        map.put("userId",userId);*/
        List<Answer> list = answerService.findList(map);
        List<AnswerVO> answerVOList=new ArrayList<>();
        for (Answer answer1 : list) {
            AnswerVO answerVO = answer2VO(answer1);
            answerVOList.add(answerVO);
        }
        PageResult<AnswerVO> answerPageResult = new PageResult<AnswerVO>((long) answerVOList.size(), answerVOList);
        return new Result(true, StatusCode.OK,"多条件查询",answerPageResult);
    }

    /**
     * 提交问卷信息:答案，完成时间，完成状态
     * @param data
     * @return
     */
    @PostMapping("/end")
    public Result end(@RequestBody String data){
        log.info("提交问卷信息:答案，完成时间，完成状态" );
        if(StringUtils.isEmpty(data)){ return  new Result(true, StatusCode.ERROR,"参数为空");}
        Answer answer = JSON.parseObject(data, Answer.class);
        answer.setEndTime(LocalDateTime.now());
        answer.setStatus("已完成");
        answerService.updateAnswer(answer);
        return new Result(true, StatusCode.OK,"提交问卷信息:答案，完成时间，完成状态");
    }

    @PostMapping("/update")
    public Result update(@RequestBody String data){
        log.info("更新问卷信息" );
        Answer answer = JSON.parseObject(data, Answer.class);
        answer.setEndTime(LocalDateTime.now());
        answerService.updateAnswer(answer);
        return new Result(true, StatusCode.OK,"更新问卷信息成功");
    }

   // @PostMapping("/anservo")
    private AnswerVO answer2VO(@RequestBody Answer answer){
       // System.out.println(data);
        //Answer answer = JSON.parseObject(data, Answer.class);
        log.info("answer2VO>>" +answer);
        Integer paperId = answer.getPaperId();//试题ID
        Paper paper = paperService.findById(paperId);//试题
        String paperName = paper.getPaper();//试题名字
        log.info("paper>>>" + paper);
        List<PaperQuestions> questionsByPaper = paperQuestionsService.findByPaperId(paperId);
        log.info("questionsByPaper>>>" + questionsByPaper);
        List<String> questionContents=new ArrayList<>();
        for (PaperQuestions paperQuestions : questionsByPaper) {
            Integer questionId = paperQuestions.getQuestionId();
            String content = questionService.findById(questionId).getContent();
            questionContents.add(content);
        }

        Integer enterpriseId = answer.getEnterpriseId();//企业ID
        System.out.println("enterpriseId>>"+enterpriseId);
        Company company = companyService.findById(enterpriseId);//企业
        System.out.println("company>>"+company);
        String companyName = company.getCompanyName();//企业名字

        log.info("companyName>>>" + companyName);
        Integer userId = answer.getUserId();
        String userName = userService.findById(userId).getName();//问卷创建者名字
        log.info("userName>>>" + userName);

        AnswerVO answerVO = new AnswerVO();
        answerVO.setPaperName(paperName);//VO试题名字
        answerVO.setEnterpriseName(companyName);//企业名字
        answerVO.setUserName(userName);//问卷创建者名字
        answerVO.setStartTime(answer.getStartTime());
        answerVO.setEndTime(answer.getEndTime());
        answerVO.setQuestions(questionContents);
        answerVO.setAnswer(answer.getAnswer());
        answerVO.setStatus(answer.getStatus());

        return answerVO;
    }



}
